package com.broadtext.message.service.impl;

import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.broadtext.common.exp.DaoException;
import com.broadtext.common.repository.EntityDao;
import com.broadtext.common.service.impl.EntityServiceImpl;
import com.broadtext.common.utils.DateUtils;
import com.broadtext.common.utils.StringUtils;
import com.broadtext.message.SMSPushUtils;
import com.broadtext.message.model.TemplateParam;
import com.broadtext.message.model.TtAlert;
import com.broadtext.message.service.ISmsService;
import com.broadtext.rms.system.model.SysUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service("smsService")
public class SmsServiceImpl extends EntityServiceImpl<TtAlert> implements ISmsService {

    private static final Logger logger = LoggerFactory.getLogger(SmsServiceImpl.class);

    /**
     *
     * <p>Description: 基类dao</p>
     * @param entityDao 基类实体dao
     */
    @Autowired
    @Qualifier("ttAlertDao")
    public void setEntityDao(EntityDao<TtAlert> entityDao) {
        super.entityDao = entityDao;
    }

    @Override
    @SuppressWarnings("unchecked")
    public void sendSms() throws DaoException {
        //第一步:查询上次发送时间
        String gatherTimeStart = this.getTasktime("sms");
        Map<String, Object> params = new HashMap<>();
        params.put("gatherTimeStart", gatherTimeStart);
        //获取当前时间
        String gatherTimeEnd = DateUtils.getCurrentTime();
        params.put("gatherTimeEnd", gatherTimeEnd);
        //第二步:查询该段时间内的告警
        List<TtAlert> alertList = this.entityDao.findByProperty("com.broadtext.message.model.TtAlert.getAlert", params);
        Date now = new Date();
        //获取当前时间
        SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss");
        String time = format.format(now).substring(0,5);
        String week = DateUtils.getWeek(now);
        Map<String, Object> queryUserParams = new HashMap<>();
        queryUserParams.put("now",time);
        queryUserParams.put("week",week);
        logger.info(">>>>>>>now time :[week {}-{}]<<<<<<<",week,time);
        /*循环嵌套，实在不妥*/
        for (TtAlert alert : alertList) {
            if (StringUtils.isBlank(alert.getPackCode())||StringUtils.isBlank(alert.getAlertCode())) {
                continue;
            }
            //获取当前时间
            queryUserParams.put("packCode",alert.getPackCode());
            queryUserParams.put("alertCode",alert.getAlertCode());
            //第三步:根据电池packCode 查询电池所属厂商下的所有的用户以及pack生产厂下的所有用户，且符合接受通知条件的人
            List<SysUser> userList = this.entityDao.findByProperty("com.broadtext.message.model.TtAlert.getSmsNoticeUser",queryUserParams);
            SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            for (SysUser user:userList) {
                if(StringUtils.isBlank(user.getPhoneNumber()))
                    continue;
                TemplateParam templateParam = new TemplateParam(user.getTruename(),alert.getPackCode(),alert.getAlertCode()+alert.getAlertName(),f.format(alert.getHappenTimeStart()));
                //循环中try catch ，避免一条发送出错，后续全部不执行
                //其实不合理，异步通知应该用消息队列模型来做，无论是可靠性还是以后的扩展性mq都更合适
                try {
                    //第四步:推送短信
                    SendSmsResponse response = SMSPushUtils.sendSms(user.getPhoneNumber(),templateParam);
                    logger.info(">>>>>>send sms to user[{}],response:{}",user.getTruename(),response.getCode());
                    //TODO 插入发送记录到数据库 以及后续的读取消息回执
                } catch (ClientException e) {
                    e.printStackTrace();
                    logger.error("send sms error...");
                }
            }
        }

        //更新时间
        updateTaskTime("sms",gatherTimeEnd);

    }

    /**
     * <p>Description: 查询结转时间</p>
     *
     * @param type 类型
     * @return string
     * @throws DaoException dao层异常
     */
    @SuppressWarnings("unchecked")
    private String getTasktime(String type) throws DaoException {
        String time = "";
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("type", type);
        List<Map<String, Object>> list = this.entityDao.findByProperty("com.broadtext.message.model.SysMessage.getTasktime", params);
        if (list != null && list.size() > 0 && list.get(0) != null) {
            time = String.valueOf(list.get(0).get("gatherTimeStart"));
        }
        return time;
    }

    /**
     *
     * <p>Description: 更新结转时间</p>
     * @param type 类型
     * @param time 时间
     * @throws DaoException dao层异常
     */
    private void updateTaskTime(String type, String time) throws DaoException{
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("type", type);
        params.put("gatherTimeEnd", time);
        this.entityDao.findByProperty("com.broadtext.message.model.SysMessage.updateTaskTime", params);
    }
}
